package com.hmdp.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result sendcode(String phone,HttpSession session) {
        if(RegexUtils.isPhoneInvalid(phone))return Result.fail("phone number wrong");
        String code = RandomUtil.randomNumbers(6);
        log.debug("验证码为：{}",code);
        session.setAttribute("code",code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.验证码校验
        String code = (String)session.getAttribute("code");
        if (code==null||!code.equals(loginForm.getCode()))return Result.fail("验证码错误");
        //2.判断用户是否存在
        User user = userMapper
                .selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, loginForm.getPhone()));
        if(user==null){
            String name = USER_NICK_NAME_PREFIX+RandomUtil.randomString(6);
            user=new User().setPhone(loginForm.getPhone()).setNickName(name);
            userMapper.insert(user);
        }
        session.setAttribute("user",user);
        return Result.ok();
    }
}
